package com.itheima.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("-----------------全局过滤器MyGlobalFilter------------------- --");
        ServerHttpRequest request = exchange.getRequest();
        //获取请求路径中的token参数
        String token = request.getQueryParams().getFirst("token");
        if (StringUtils.isBlank(token)){
            //如果token不存在，设置响应状态码为未授权
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            //响应完成，不在进行后面的过滤操作
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }
    //设置过滤器的执行顺序。返回的数字越小，约先执行
    @Override
    public int getOrder() {
        return 1;
    }
}
